﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.IO;

namespace HTMLConverter
{
    [ValueConversion(typeof(string), typeof(FlowDocument))]
    public class HtmlToFlowDocConverter : UIElement, IValueConverter
    {
        private FlowDocument _flowDocument;
        
        public FlowDocument Document { get { return _flowDocument;} }
        
        public static readonly RoutedEvent DocumentReadyEvent = 
            EventManager.RegisterRoutedEvent("DocumentReady", RoutingStrategy.Direct, 
                typeof(RoutedEventHandler), typeof(HtmlToFlowDocConverter));

        public event RoutedEventHandler DocumentReady
        {
            add{ AddHandler(DocumentReadyEvent, value); }
            remove{ RemoveHandler(DocumentReadyEvent, value); }
        }
        
        public object Convert(object value, Type targetType, object parameter,
                              System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                _flowDocument = new FlowDocument();
                string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(value.ToString(), false);

                using (MemoryStream stream = new MemoryStream((new ASCIIEncoding()).GetBytes(xaml)))
                {
                    TextRange text = new TextRange(_flowDocument.ContentStart, _flowDocument.ContentEnd);
                    text.Load(stream, DataFormats.Xaml);
                }

                OnDocumentReady();
                return _flowDocument;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
                                  System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
        private void OnDocumentReady()
        {
            RoutedEventArgs e = new RoutedEventArgs(DocumentReadyEvent, this);
            RaiseEvent(e);
        }
        
    }
}
